package com.example.studentknowledgesys.service.impl;

import com.example.studentknowledgesys.controller.ArticleController;
import com.example.studentknowledgesys.dao.ArticleMapper;
import com.example.studentknowledgesys.dao.TagMapper;
import com.example.studentknowledgesys.dto.ArticleDetailDTO;
import com.example.studentknowledgesys.entity.Article;
import com.example.studentknowledgesys.entity.PointRule;
import com.example.studentknowledgesys.entity.Tag;
import com.example.studentknowledgesys.service.ArticleService;
import com.example.studentknowledgesys.service.PointService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author 光的代言人
 */
@Service("articleService")
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private PointService pointService;
    @Autowired
    private TagMapper tagMapper;

    @Override
    public Article createArticle(Article article) {
        return null;
    }

    /**
     * 创建文章
     *
     * @param article
     * @return
     */
//    @Override
//    public Article createArticle(Article article) {
//        // 验证标签是否存在
//        if (article.getTagId() != null) {
//            Tag tag = tagMapper.selectTagById(article.getTagId());
//            if (tag == null) {
//                throw new RuntimeException("标签不存在");
//            }
//        }
//
//        // 设置创建时间
//        article.setCreatedAt(String.valueOf(new Date()));
//        article.setUpdatedAt(String.valueOf(new Date()));
//
//        articleMapper.insertArticle(article);
//        return article;
//    }

    @Transactional
    @Override
    public ArticleController.ArticleResponse createArticle(ArticleController.ArticleRequest request) {
        // 创建文章对象
        Article article = new Article();
        article.setTitle(request.getTitle());
        article.setContent(request.getContent());
        article.setTagId(request.getTagId());
        article.setAuthorId(request.getAuthorId());
        article.setCreatedAt(String.valueOf(new Date()));
        article.setUpdatedAt(String.valueOf(new Date()));

        // 保存文章
        articleMapper.insertArticle(article);

        int pointsAwarded = 0;
        // 看是否符合积分规则，如果符合积分规则，就奖励积分
        // 如果不是草稿，则奖励积分
        if (!request.isDraft()) {
            // 奖励基础积分
            pointsAwarded += pointService.awardPoints(article.getAuthorId(), "ARTICLE_CREATE",
                    "发布了文章: " + article.getTitle());

            // 计算字数积分
            int wordCount = article.getContent().length();
            PointRule wordCountRule = pointService.getRuleByType("ARTICLE_WORD_COUNT");
            if (wordCountRule != null && wordCountRule.getIsActive() && wordCount > 0) {
                int basePoints = wordCountRule.getPointValue();
                int extraPoints = (wordCount / 500) * basePoints;
                if (extraPoints > 0) {
                    pointService.awardPoints(article.getAuthorId(), "ARTICLE_WORD_COUNT",
                            extraPoints, "文章字数奖励: " + article.getTitle());
                    pointsAwarded += extraPoints;
                }
            }

            // 检查图片奖励
            if (articleContainsImages(article)) {
                pointsAwarded += pointService.awardPoints(article.getAuthorId(), "ARTICLE_HAS_IMAGE",
                        "文章配图奖励: " + article.getTitle());
            }

            // 检查视频奖励
            if (articleContainsVideos(article)) {
                pointsAwarded += pointService.awardPoints(article.getAuthorId(), "ARTICLE_HAS_VIDEO",
                        "文章视频奖励: " + article.getTitle());
            }
        }

        // 构建响应对象
        ArticleController.ArticleResponse response = new ArticleController.ArticleResponse();
        response.setArticle(article);
        response.setPointsAwarded(pointsAwarded);
        return response;
    }

    private boolean articleContainsImages(Article article) {
        // 简化实现：检查是否包含<img标签
        return article.getContent().contains("<img");
    }

    private boolean articleContainsVideos(Article article) {
        // 简化实现：检查是否包含<video标签或YouTube嵌入
        return article.getContent().contains("<video") ||
                article.getContent().contains("youtube.com/embed");
    }

    /**
     * 更新文章
     *
     * @param article
     * @return
     */
    @Override
    public Article updateArticle(Article article) {
        // 验证文章是否存在
        Article existingArticle = articleMapper.selectArticleById(article.getId());
        if (existingArticle == null) {
            throw new RuntimeException("文章不存在");
        }

        // 验证标签是否存在
        if (article.getTagId() != null) {
            Tag tag = tagMapper.selectTagById(article.getTagId());
            if (tag == null) {
                throw new RuntimeException("标签不存在");
            }
        }

        // 更新文章
        article.setUpdatedAt(String.valueOf(new Date()));
        articleMapper.updateArticle(article);
        return articleMapper.selectArticleById(article.getId());
    }

    @Override
    public boolean updateArticleStatus(Long id, Integer status) {
        return articleMapper.updateArticleStatus(id, status) > 0;
    }

    @Override
    public boolean deleteArticle(Long id) {
        Article article = articleMapper.selectArticleById(id);
        if (article == null) {
            return false;
        }

        articleMapper.deleteArticleById(id);
        return true;
    }

    @Override
    public Article getArticleById(Long id) {
        return articleMapper.selectArticleById(id);
    }

    @Override
    public List<Article> getAllArticles() {
        return articleMapper.selectAllArticles();
    }

    @Override
    public List<Article> getArticlesByTag(Long tagId) {
        return articleMapper.selectArticlesByTagId(tagId);
    }
    @Override
    public List<ArticleDetailDTO> getArticleDetails(String tagName,Long authorId) {
        return articleMapper.getArticleDetails(tagName,authorId);
    }

    @Override
    public ArticleDetailDTO getArticleDetail(Long articleId) {
        return articleMapper.getSingleArticleDetail(articleId);
    }

    @Override
    public int updateArticleById(Article article) {
        return articleMapper.updateArticleById(article);
    }


}
